<template>
  <div>
    <el-dialog
      :title="`${formData.id ? '修改' : '增加'}学科`"
      :visible="dialogVisible"
      width="40%"
      @close="close"
    >
      <el-form ref="formRef" :model="formData" :rules="rules">
        <el-form-item label="学科名称" prop="subject_name" label-width="140px">
          <el-input
            v-model="formData.subject_name"
            placeholder="请输入学科名称"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort" label-width="140px">
          <el-input-number
            v-model="formData.sort"
            label="排序"
          />
        </el-form-item>
        <el-form-item label="是否显示" prop="is_show" label-width="140px">
          <el-switch
            :value="formData.is_show === 1 ? true : false"
            @change="toggleShowState"
          />
        </el-form-item>
        <el-form-item label="学科图标" label-width="140px">
          <el-upload
            action=""
            :on-preview="handlePreview"
            :on-remove="onRemove"
            :before-upload="beforeUpload"
            :http-request="httpRequest"
            :on-change="onChange"
            list-type="picture-card"
            :limit="1"
            :file-list="filelist"
          >
            <i class="el-icon-plus" />
            <div slot="tip" class="el-upload__tip">建议尺寸200x200</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
    <perview-image ref="prevImg" :dialog-visible.sync="isPreviewShow" />
  </div>
</template>

<script>
import PerviewImage from './perview-image.vue'
import {
  imageUpload,
  addSubjectData,
  editSubjectData,
  fetchSubjectData
} from '@/api/subject_c'

export default {
  name: 'EditSubject',
  components: {
    PerviewImage
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        sort: 10,
        is_show: 1
      },
      rules: {
        subject_name: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ],
        sort: [{ required: true, message: '必填', trigger: 'blur' }],
        is_show: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      filelist: [], // 图片列表，用于回显
      isPreviewShow: false, // 是否显示图片预览窗口
      currentFile: null
    }
  },
  methods: {
    toggleShowState(value) {
      this.formData.is_show = value ? 1 : 2
    },
    // 加载课程数据，用于修改时回显
    async loadSubjectData(id) {
      const resp = await fetchSubjectData(id)
      this.formData = resp.data
      resp.data.subject_icon &&
        this.filelist.push({
          name: 'avatar.jpg',
          url: 'http://122.51.249.55:7005/' + resp.data.subject_icon,
          path: resp.data.subject_icon,
          upload: true
        })
    },
    async submit() {
      await this.$refs.formRef.validate()
      if (this.filelist[0] && !this.filelist[0].upload) {
        return this.$message.warning('图片正在上传')
      }
      if (this.formData.id) {
        const resp = await editSubjectData({
          ...this.formData,
          subject_icon: this.filelist[0] ? this.filelist[0].path : ''
        })
        if (!resp.success) {
          return this.$message.error(resp.msg)
        }
        this.$message.success('修改课程成功')
      } else {
        const resp = await addSubjectData({
          ...this.formData,
          subject_icon: this.filelist[0] && this.filelist[0].path
        })
        if (!resp.success) {
          return this.$message.error(resp.msg)
        }
        this.$message.success('添加课程成功')
      }

      this.$emit('update-list')
      this.close()
    },
    // 删除行
    async delRow() {},
    handlePreview(file) {
      this.$refs.prevImg.imgUrl = file.url
      this.isPreviewShow = true
    },

    onRemove(file) {
      this.filelist = this.filelist.filter((item) => item.uid !== file.uid)
    },

    beforeUpload(file) {
      const MAX_SIZE = 5
      if (file.size / 1024 / 1024 > MAX_SIZE) {
        this.$message.error(`图片大小不能超过${MAX_SIZE} M`)
        return false
      }
      const accecpedType = [
        'image/jpeg',
        'image/jpg',
        'image/png',
        'image/gif',
        'image/webp'
      ]
      if (!accecpedType.includes(file.type)) {
        this.$message.error('不被支持的图片格式')
        return false
      }
      this.currentFile = file
    },
    onChange(file, filelist) {
      this.filelist = filelist.map((item) => item)
    },
    async httpRequest({ file }) {
      const fd = new FormData()
      fd.append('file', file)
      const resp = await imageUpload(fd, {
        mode: 'single',
        type: 'image'
      })
      if (!resp.success) {
        return this.$message.error(resp.msg)
      }

      this.filelist = this.filelist.map((item) => {
        if (item.uid === this.currentFile.uid) {
          item.url = 'http://122.51.249.55:7005/' + resp.data.url
          item.upload = true
          item.path = resp.data.url
        }
        return item
      })
    },
    close() {
      this.formData = {
        sort: 10,
        is_show: 1
      }
      this.filelist = []
      this.$emit('update:dialog-visible', false)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  padding: 15px 20px 10px !important;
  border-bottom: 1px solid #e9ecef;
}
::v-deep .el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
::v-deep .el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
}
::v-deep .el-upload__tip {
  font-size: 14px;
}
</style>
